<?php
declare(strict_types=1);

/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/30
 * Time: 9:58
 */

namespace App\Libs;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\Logger;
use Hyperf\Logger\LoggerFactory;
use Hyperf\HttpServer\Contract\ResponseInterface;

class DiyError
{
    #[Inject]
    protected ResponseInterface $response;

    protected Logger $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        //第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'api');
    }



    /**
     * 记录日志返回错误代码
     * @param $exception
     * @return object
     */
    public function errorJson($exception): object
    {
        if (is_object($exception)) {
            $msg = '[' . date('Y-m-d H:i:s', time()) . '] ' . $exception->getFile() . ' | ' . $exception->getLine() . ' | ' . $exception->getMessage();
        } else {
            $msg = $exception;
        }
        $this->logger->info($msg);
        $dev = config('app_env');
        if($dev=='test'){
            return $this->response->json(['code' => 50001, 'message' => $exception->getFile() . ' | ' . $exception->getLine() . ' | ' . $exception->getMessage(),]);
        }else{
            return $this->response->json(['code' => 50001, 'message' => '系统异常']);
        }
    }


    /**
     * 写入错误日志
     * @param $exception
     * @return bool
     */
    public function errorLog($exception): bool
    {
        if (is_object($exception)) {
            $msg = '[' . date('Y-m-d H:i:s', time()) . '] ' . $exception->getFile() . ' | ' . $exception->getLine() . ' | ' . $exception->getMessage();
        } else {
            $msg = $exception;
        }
        $this->logger->info($msg);
        return true;
    }

}